<script setup lang="ts">
import {addApi, deleteApi, getDeptApi, queryAllApi, updateApi} from "@/api/dept"
import type { DeptModel } from "@/api/model/model"
import { ElMessage, ElMessageBox, type FormRules, type FormInstance } from "element-plus"
import { ref, onMounted } from "vue"

// 新增部门
const dialogFormVisible = ref<boolean>(false)
const deptForm = ref<DeptModel>({name:''})
let formTitle = ref<string>('')
const add = () => {
  dialogFormVisible.value = true;
  formTitle.value = '新增部门';
  deptForm.value = {name:''};
  resetForm(deptFormRef.value); //重置校验信息
}
const save = async (formEl: FormInstance | undefined) =>{
  // 保存数据之前，先校验表单是否合法
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {    // valid--true,代表表单校验成功
      // 优化---需要判断是新增还是修改
      let result = null;
      //1.发送异步请求
      if(deptForm.value.id){    //--id有值代表修改
        result = await updateApi(deptForm.value);
      }else{                    //--id没有值代表新增
        result =await addApi(deptForm.value);
      }

      //2.获取数据
      if (result.code) {
        //成功响应
        dialogFormVisible.value = false;
        queryAll();
        ElMessage.success('操作成功');
      }else{
        //失败响应
        ElMessage.error(result.msg);
      }
    }
  })
}
const update =  async (id:number) => {
  dialogFormVisible.value = true;
  formTitle.value = '修改部门';
  deptForm.value = {name:''};
  resetForm(deptFormRef.value); //重置校验信息

  console.log("id="+id);
  // 发送异步请求，根据id查询部门
  const result = await getDeptApi(id);
  if(result.code) {
    deptForm.value = result.data;
  }
}
const deleteById = (id:number) => {
  ElMessageBox.confirm('您确认是否要删除该数据？','删除部门',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {  //成功回调函数---点击确认按钮的时候触发
      // 发送异步请求，删除部门数据
      const result = await deleteApi(id);
      if(result.code) {
        // 刷新页面
        queryAll();
        ElMessage.success('删除成功');
      }else{
        ElMessage.error(result.msg);
      }
    }).catch(() => {//失败回调函数---点击取消按钮的时候触发
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const deptList = ref([])
const queryAll = async ()=>{
  const result = await queryAllApi()
  console.log(result)
  deptList.value = result.data
}
onMounted(()=>{
  queryAll()
})

// 定义校验规则
const deptFormRef = ref<FormInstance>()     //定义表单对象
const rules = ref<FormRules<DeptModel>>({
  name: [
    // 判断是否为空，如果为空，则响应message信息，trigger：blur代表离焦事件
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    // 判断名称的长度在min~max之前，如果不满足条件，则响应message
    { min: 2, max: 10, message: '长度必须为2-10位', trigger: 'blur' },
  ]
})
// 重置校验信息
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<template>
  <h1>部门管理</h1> <br>
  <!-- 按钮 -->
  <el-button type="primary" style="float:right" @click="add">+ 新增部门</el-button> <br><br>
  <!-- 表格 -->
  <el-table :data="deptList" border style="width: 100%">
    <!-- type="index"用于展示数据列表的序号，从1开始展示 -->
    <el-table-column type="index" label="序号" width="150" align="center"/>
    <el-table-column prop="name" label="部门名称" width="250" align="center"/>
    <el-table-column prop="updateTime" label="最后操作时间" width="250" align="center"/>
    <el-table-column prop="address" label="操作" align="center">
      <template #default="scope">
        <el-button size="small" type="primary" @click="update(scope.row.id)">修改</el-button>
        <el-button size="small" type="danger" @click="deleteById(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 新增|修改对话框 -->
  <el-dialog v-model="dialogFormVisible" :title="formTitle" width="500">
    <el-form :model="deptForm" :rules="rules" ref="deptFormRef">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="deptForm.name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save(deptFormRef)">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>
